package cn.edu.henu.team.ui;

import android.content.Intent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.UpdateListener;
import cn.edu.henu.team.MPChart.BarAnalyseActivity;
import cn.edu.henu.team.MPChart.LineAnalyseActivity;
import cn.edu.henu.team.R;
import cn.edu.henu.team.adapter.MyBaseAdapter;
import cn.edu.henu.team.base.BaseActivity;
import cn.edu.henu.team.bean.diagnosticLog;
import cn.edu.henu.team.bean.familyCircle;
import cn.edu.henu.team.bean.gridViewIcon;
import cn.edu.henu.team.table.diagLog;
import cn.edu.henu.team.table.diagLogUtils;
import cn.edu.henu.team.table.health_f;
import cn.edu.henu.team.table.health_p;
import cn.edu.henu.team.table.healthfUtils;
import cn.edu.henu.team.table.healthpUtils;
import cn.edu.henu.team.ui_test.AllUploadLogActivity;
import cn.edu.henu.team.ui_test.DiagnoseLogActivity;

public class CircleShareActivity extends BaseActivity {
    private GridView grid_photo;
    private BaseAdapter mAdapter = null;
    private ArrayList<gridViewIcon> mData = null;
    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

    private String objectID;
    private String userName;
    private String recordId;
    private ImageView back;
    private TextView nickName;
    private TextView delete;

    @Override
    protected int initLayout() {
        return R.layout.activity_circle_share;
    }

    @Override
    protected void initView() {
        objectID = getIntent().getStringExtra("objectId");
        userName = getIntent().getStringExtra("username");
        recordId = getIntent().getStringExtra("recordId");

        back = findViewById(R.id.back);
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        nickName = findViewById(R.id.nickName);
        nickName.setText(userName);
        grid_photo = findViewById(R.id.grid_photo);

        delete = findViewById(R.id.delete);
        delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                familyCircle m = new familyCircle();
                m.setObjectId(recordId);
                m.delete(new UpdateListener() {
                    @Override
                    public void done(BmobException e) {
                        if(e == null){
                            Toast.makeText(mContext, "该用户已移除家庭圈", Toast.LENGTH_SHORT).show();
                            finish();
                        }
                    }
                });
            }
        });
    }

    @Override
    protected void initData() {
        mData = new ArrayList<gridViewIcon>();
        mData.add(new gridViewIcon(R.mipmap.iv_icon_1, "诊断记录"));
        mData.add(new gridViewIcon(R.mipmap.iv_icon_4, "查看上传记录"));
        mData.add(new gridViewIcon(R.mipmap.iv_icon_3, "健康分析(评测概率)"));
        mData.add(new gridViewIcon(R.mipmap.iv_icon_5, "健康分析(就诊指数)"));

        mAdapter = new MyBaseAdapter<gridViewIcon>(mData, R.layout.item_grid_icon) {
            @Override
            public void bindView(ViewHolder holder, gridViewIcon obj) {
                holder.setImageResource(R.id.img_icon, obj.getiId());
                holder.setText(R.id.txt_icon, obj.getiName());
            }
        };

        grid_photo.setAdapter(mAdapter);

        grid_photo.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //Toast.makeText(mContext, "你点击了~" + position + "~项", Toast.LENGTH_SHORT).show();
                switch (position) {
                    case 0:
                        BmobQuery<diagnosticLog> query0 = new BmobQuery("diagnosticLog");
                        query0.addWhereEqualTo("userID", objectID);
                        query0.order("-createdAt");
                        query0.findObjects(new FindListener<diagnosticLog>() {
                            @Override
                            public void done(List<diagnosticLog> list, BmobException e) {
                                if (e == null) {
                                    if (list != null) {
                                        diagLogUtils.deleteAll();
                                        for (diagnosticLog t : list) {
                                            diagLog mDiagLog = new diagLog();
                                            mDiagLog.setObjectId(t.getObjectId());
                                            mDiagLog.setContent(t.getContent());
                                            mDiagLog.setCreatedAt(t.getCreatedAt());
                                            mDiagLog.setAnswer(t.getAnswer());
                                            int year = Integer.parseInt(t.getCreatedAt().substring(0, 4));
                                            int month = Integer.parseInt(t.getCreatedAt().substring(5, 7));
                                            mDiagLog.setYear(year);
                                            mDiagLog.setMonth(month);
                                            diagLogUtils.insert(mDiagLog);
                                        }
                                        startActivity(new Intent(CircleShareActivity.this, DiagnoseLogActivity.class));
                                    } else {
                                        Toast.makeText(CircleShareActivity.this, "服务器数据为空~", Toast.LENGTH_SHORT).show();
                                    }
                                } else {
                                    Toast.makeText(CircleShareActivity.this, "查询失败" + e.getMessage(), Toast.LENGTH_SHORT).show();
                                }
                            }
                        });
                        break;
                    case 1:
                        Intent it = new Intent(CircleShareActivity.this, AllUploadLogActivity.class);
                        it.putExtra("objectId",objectID);
                        startActivity(it);
                        break;
                    case 2:
                        healthpUtils.deleteAll();
                        for (int year = 2021; year <= 2024; year++) {
                            for (int month = 1; month <= 12; month++) {
                                for (int day = 1; day <= 30; day++) {
                                    health_p mHealth = new health_p();
                                    float p1 = Math.round(Math.random() * 50 + 10);
                                    mHealth.setP1(p1);
                                    float p2 = Math.round(Math.random() * 50 + 10);
                                    mHealth.setP2(p2);
                                    float p3 = Math.round(Math.random() * 50 + 10);
                                    mHealth.setP3(p3);
                                    mHealth.setYear(year);
                                    mHealth.setMonth(month);
                                    mHealth.setDay(day);
                                    healthpUtils.insert(mHealth);
                                }
                            }
                        }
                        startActivity(new Intent(CircleShareActivity.this, LineAnalyseActivity.class));
//                        BmobQuery<diagnosticLog> query = new BmobQuery<diagnosticLog>();
//                        query.addWhereEqualTo("user", BmobUser.getCurrentUser(_User.class));
//                        query.average(new String[]{"p1", "p2", "p3"});
//                        query.groupby(new String[]{"createdAt"});
//                        query.findStatistics(diagnosticLog.class, new QueryListener<JSONArray>() {
//                            @Override
//                            public void done(JSONArray jsonArray, BmobException e) {
//                                if (e == null) {
//                                    if (jsonArray != null) {
//                                        int length = jsonArray.length();
//                                        try {
//                                            healthpUtils.deleteAll();
//                                            for (int i = 0; i < length; i++) {
//                                                JSONObject obj = jsonArray.getJSONObject(i);
//                                                health_p mHealth = new health_p();
//                                                mHealth.setP1(Float.parseFloat(obj.getString("_avgP1")));
//                                                mHealth.setP1(Float.parseFloat(obj.getString("_avgP2")));
//                                                mHealth.setP1(Float.parseFloat(obj.getString("_avgP3")));
//                                                Log.d("*****","*****"+Float.parseFloat(obj.getString("_avgP1")));
//                                                int year = Integer.parseInt(obj.getString("createdAt").substring(0,4));
//                                                int month = Integer.parseInt(obj.getString("createdAt").substring(5,7));
//                                                int day = Integer.parseInt(obj.getString("createdAt").substring(8));
//                                                mHealth.setYear(year);
//                                                mHealth.setMonth(month);
//                                                mHealth.setDay(day);
//                                                healthpUtils.insert(mHealth);
//                                            }
//                                            startActivity(new Intent(getActivity(), LineAnalyseActivity.class));
//                                        } catch (JSONException e1) {
//                                            e1.printStackTrace();
//                                        }
//                                    } else {
//                                        Toast.makeText(getContext(), "服务器数据为空~", Toast.LENGTH_SHORT).show();
//                                    }
//                                } else {
//                                    Log.d("******", e.toString());
//                                }
//                            }
//                        });
                        break;
                    case 3:
                        healthfUtils.deleteAll();
                        for (int year = 2021; year <= 2024; year++) {
                            for (int month = 1; month <= 12; month++) {
                                for (int day = 1; day <= 30; day++) {
                                    health_f mHealth = new health_f();
                                    mHealth.setNum1(((int) (10 * Math.random())) % 2);
                                    mHealth.setNum2(((int) (10 * Math.random())) % 2);
                                    mHealth.setNum3(((int) (10 * Math.random())) % 2);
                                    mHealth.setYear(year);
                                    mHealth.setMonth(month);
                                    mHealth.setDay(day);
                                    healthfUtils.insert(mHealth);
                                }
                            }
                        }
                        startActivity(new Intent(CircleShareActivity.this, BarAnalyseActivity.class));
//                        BmobQuery<diagnosticLog> query4 = new BmobQuery<diagnosticLog>();
//                        query4.addWhereEqualTo("user", BmobUser.getCurrentUser(_User.class));
//                        query4.sum(new String[]{"findDN1", "findDN2", "findDN3"});
//                        query4.groupby(new String[]{"createdAt"});
//                        //是否返回所统计的总条数
//                        query4.setHasGroupCount(true);
//                        query4.findStatistics(diagnosticLog.class, new QueryListener<JSONArray>() {
//                            @Override
//                            public void done(JSONArray jsonArray, BmobException e) {
//                                if (e == null) {
//                                    if (jsonArray != null) {
//                                        int length = jsonArray.length();
//                                        try {
//                                            healthfUtils.deleteAll();
//                                            for (int i = 0; i < length; i++) {
//                                                JSONObject obj = jsonArray.getJSONObject(i);
//                                                health_f mHealth = new health_f();
//                                                mHealth.setNum1(obj.getInt("_sumFindDN1"));
//                                                mHealth.setNum2(obj.getInt("_sumFindDN2"));
//                                                mHealth.setNum3(obj.getInt("_sumFindDN3"));
//                                                mHealth.setCreatedAt(obj.getString("createdAt"));
//                                                mHealth.setCountSum(obj.getInt("_count"));  // 当天有多少评测数据
//                                                int year = Integer.parseInt(obj.getString("createdAt").substring(0,4));
//                                                int month = Integer.parseInt(obj.getString("createdAt").substring(5,7));
//                                                int day = Integer.parseInt(obj.getString("createdAt").substring(8));
//                                                mHealth.setYear(year);
//                                                mHealth.setMonth(month);
//                                                mHealth.setDay(day);
//                                                healthfUtils.insert(mHealth);
//                                            }
//                                            startActivity(new Intent(getActivity(), BarAnalyseActivity.class));
//                                        } catch (JSONException e1) {
//                                            e1.printStackTrace();
//                                        }
//                                    } else {
//                                        Toast.makeText(getContext(), "服务器数据为空~", Toast.LENGTH_SHORT).show();
//                                    }
//                                } else {
//                                    Log.d("******", e.toString());
//                                }
//                            }
//                        });
                        break;
                    default:
                        break;
                }
            }
        });
    }
}